use actix_session::Session;
use actix_web::web;

use crate::{
    database::{table, DbPool},
    route::form::user::{LoginForm, NewUserForm, UserForm},
    service::ServiceError,
    srv_add, srv_del, srv_get_by_slug, srv_get_in_page, srv_upd,
};

srv_add!(add, NewUserForm, table::user::crud::create);
srv_upd!(upd, UserForm, table::user::crud::update);
srv_del!(del, table::user::crud::delete);

srv_get_in_page!(
    get_in_page,
    UserForm,
    table::user::crud::read_count_from_offset
);
srv_get_by_slug!(
    get_by_username,
    UserForm,
    table::user::crud::read_by_username
);

pub async fn login(
    pool: web::Data<DbPool>,
    session: Session,
    form: LoginForm,
) -> Result<UserForm, ServiceError> {
    if session.get::<String>("uid")?.is_some() {
        return Err(ServiceError::from("user already login!"));
    }
    let user = get_by_username(pool.clone(), form.username).await?;
    if user.password != form.password {
        return Err(ServiceError::from("user not found or wrong password"));
    }
    session.insert("uid", user.id.to_string())?;
    Ok(user)
}
